package com.study.springboot;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

/**
 * @author lupengwei
 */
public class MyWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(final ServletContext servletContext) throws ServletException {
        System.out.println("初始化容器, 配置 DispatcherServlet");
        // 通过注解的方式初始化 Spring 的上下文
        AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        // 注册 Spring 配置类（替代传统项目中 XML 的 Configuration）
        applicationContext.register(SpringApplicationConfig.class);
        applicationContext.refresh();
        
        // 基于java代码的方式初始化 DispatcherServlet
        DispatcherServlet servlet = new DispatcherServlet(applicationContext);
        ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);
        registration.setLoadOnStartup(1);
        registration.addMapping("/app/*");
        System.out.println("完成初始化容器, 完成配置 DispatcherServlet");
    }
}